<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统设置 - 百日行动线索收集系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <link href="css/admin-mobile.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            width: 250px;
            z-index: 1000;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 10px;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
        .navbar {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .content-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        .setting-item {
            padding: 15px 0;
            border-bottom: 1px solid #e9ecef;
        }
        .setting-item:last-child {
            border-bottom: none;
        }
        .setting-label {
            font-weight: 500;
            margin-bottom: 5px;
        }
        .setting-description {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <!-- 移动端头部 -->
    <div class="mobile-header">
        <button class="mobile-menu-btn" onclick="toggleSidebar()">
            <i class="bi bi-list"></i>
        </button>
        <h5 class="mb-0">系统设置</h5>
        <div class="dropdown">
            <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                <i class="bi bi-person-circle"></i>
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item" href="#" onclick="logout()"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
            </ul>
        </div>
    </div>
    
    <!-- 侧边栏遮罩层 -->
    <div class="sidebar-overlay"></div>
    
    <!-- 侧边栏 -->
    <nav class="sidebar" id="sidebar">
        <div class="p-3">
            <h5 class="text-white mb-4">
                <i class="bi bi-shield-check me-2"></i>
                管理后台
            </h5>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="/admin/dashboard.html">
                        <i class="bi bi-speedometer2 me-2"></i>仪表板
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/clues.html">
                        <i class="bi bi-file-text me-2"></i>线索管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/statistics.html">
                        <i class="bi bi-bar-chart me-2"></i>统计分析
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/users.html">
                        <i class="bi bi-people me-2"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/admin/settings.html">
                        <i class="bi bi-gear me-2"></i>系统设置
                    </a>
                </li>
            </ul>
        </div>
        <div class="mt-auto p-3">
            <button class="btn btn-outline-light btn-sm w-100" onclick="logout()">
                <i class="bi bi-box-arrow-right me-2"></i>退出登录
            </button>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand-lg navbar-light">
            <div class="container-fluid">
                <h4 class="mb-0">系统设置</h4>
                <div class="navbar-nav ms-auto">
                    <div class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle me-2"></i>
                            <span id="adminName">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 系统信息 -->
        <div class="content-card">
            <h5 class="mb-3"><i class="bi bi-info-circle me-2"></i>系统信息</h5>
            <div class="row">
                <div class="col-md-6">
                    <div class="setting-item">
                        <div class="setting-label">系统名称</div>
                        <div class="setting-description">百日行动线索收集系统</div>
                    </div>
                    <div class="setting-item">
                        <div class="setting-label">系统版本</div>
                        <div class="setting-description">v1.0.0</div>
                    </div>
                    <div class="setting-item">
                        <div class="setting-label">数据库状态</div>
                        <div class="setting-description">
                            <span class="badge bg-success">正常连接</span>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="setting-item">
                        <div class="setting-label">服务器时间</div>
                        <div class="setting-description" id="serverTime">-</div>
                    </div>
                    <div class="setting-item">
                        <div class="setting-label">运行环境</div>
                        <div class="setting-description">Node.js + MySQL</div>
                    </div>
                    <div class="setting-item">
                        <div class="setting-label">系统状态</div>
                        <div class="setting-description">
                            <span class="badge bg-success">运行正常</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 个人资料设置 -->
        <div class="content-card">
            <h5 class="mb-3"><i class="bi bi-person me-2"></i>个人资料</h5>
            <form id="profileForm">
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" id="profileUsername" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">真实姓名</label>
                            <input type="text" class="form-control" id="profileRealName">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="profileEmail">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">联系电话</label>
                            <input type="tel" class="form-control" id="profilePhone">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">所属部门</label>
                            <input type="text" class="form-control" id="profileDepartment">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色</label>
                            <input type="text" class="form-control" id="profileRole" readonly>
                        </div>
                    </div>
                </div>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-primary" onclick="updateProfile()">
                        <i class="bi bi-check-circle me-1"></i>保存资料
                    </button>
                    <button type="button" class="btn btn-outline-warning" onclick="showChangePasswordModal()">
                        <i class="bi bi-key me-1"></i>修改密码
                    </button>
                </div>
            </form>
        </div>

        <!-- 系统配置 -->
        <div class="content-card">
            <h5 class="mb-3"><i class="bi bi-gear me-2"></i>系统配置</h5>
            <div class="setting-item">
                <div class="setting-label">线索分类管理</div>
                <div class="setting-description">管理线索分类和优先级设置</div>
                <button class="btn btn-outline-primary btn-sm" onclick="manageClueCategoriesModal()">
                    <i class="bi bi-tags me-1"></i>管理分类
                </button>
            </div>
            <div class="setting-item">
                <div class="setting-label">数据备份</div>
                <div class="setting-description">备份系统数据和配置</div>
                <button class="btn btn-outline-success btn-sm" onclick="backupData()">
                    <i class="bi bi-download me-1"></i>立即备份
                </button>
            </div>
            <div class="setting-item">
                <div class="setting-label">系统日志</div>
                <div class="setting-description">查看系统操作日志</div>
                <button class="btn btn-outline-info btn-sm" onclick="viewSystemLogs()">
                    <i class="bi bi-file-text me-1"></i>查看日志
                </button>
            </div>
            <div class="setting-item">
                <div class="setting-label">清理缓存</div>
                <div class="setting-description">清理系统缓存和临时文件</div>
                <button class="btn btn-outline-warning btn-sm" onclick="clearCache()">
                    <i class="bi bi-trash me-1"></i>清理缓存
                </button>
            </div>
        </div>

        <!-- 统计信息 -->
        <div class="content-card">
            <h5 class="mb-3"><i class="bi bi-bar-chart me-2"></i>系统统计</h5>
            <div class="row">
                <div class="col-md-3">
                    <div class="text-center">
                        <h4 class="text-primary" id="totalCluesCount">-</h4>
                        <small class="text-muted">总线索数</small>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="text-center">
                        <h4 class="text-success" id="totalUsersCount">-</h4>
                        <small class="text-muted">管理员数</small>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="text-center">
                        <h4 class="text-warning" id="todayCluesCount">-</h4>
                        <small class="text-muted">今日新增</small>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="text-center">
                        <h4 class="text-info" id="pendingCluesCount">-</h4>
                        <small class="text-muted">待处理</small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改密码模态框 -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">修改密码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="changePasswordForm">
                        <div class="mb-3">
                            <label class="form-label">当前密码</label>
                            <input type="password" class="form-control" id="currentPassword" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">新密码</label>
                            <input type="password" class="form-control" id="newPassword" required>
                            <div class="form-text">密码长度至少6个字符</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">确认新密码</label>
                            <input type="password" class="form-control" id="confirmNewPassword" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitChangePassword()">确认修改</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/admin-mobile.js"></script>
    <script>
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadProfile();
            loadSystemStats();
            updateServerTime();
            
            // 每分钟更新一次服务器时间
            setInterval(updateServerTime, 60000);
        });

        // 检查认证状态
        function checkAuth() {
            const token = localStorage.getItem('adminToken');
            if (!token) {
                window.location.href = '/admin/login.html';
                return;
            }
            
            const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
            document.getElementById('adminName').textContent = adminUser.real_name || '管理员';
        }

        // 加载个人资料
        async function loadProfile() {
            try {
                const token = localStorage.getItem('adminToken');
                const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
                
                // 从本地存储加载基本信息
                document.getElementById('profileUsername').value = adminUser.username || '';
                document.getElementById('profileRealName').value = adminUser.real_name || '';
                document.getElementById('profileEmail').value = adminUser.email || '';
                document.getElementById('profilePhone').value = adminUser.phone || '';
                document.getElementById('profileDepartment').value = adminUser.department || '';
                document.getElementById('profileRole').value = getRoleText(adminUser.role) || '';
                
            } catch (error) {
                console.error('加载个人资料失败:', error);
            }
        }

        // 加载系统统计
        async function loadSystemStats() {
            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch('/api/admin/statistics/overview', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    const data = result.data;
                    
                    document.getElementById('totalCluesCount').textContent = data.total_clues || 0;
                    document.getElementById('todayCluesCount').textContent = data.today_clues || 0;
                    document.getElementById('pendingCluesCount').textContent = data.pending_clues || 0;
                }
                
                // 加载管理员数量
                const usersResponse = await fetch('/api/admin/users?page=1&page_size=1', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (usersResponse.ok) {
                    const usersResult = await usersResponse.json();
                    document.getElementById('totalUsersCount').textContent = usersResult.data.pagination.total || 0;
                }
                
            } catch (error) {
                console.error('加载系统统计失败:', error);
            }
        }

        // 更新服务器时间
        function updateServerTime() {
            const now = new Date();
            document.getElementById('serverTime').textContent = now.toLocaleString('zh-CN');
        }

        // 更新个人资料
        async function updateProfile() {
            try {
                const token = localStorage.getItem('adminToken');
                const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
                
                const profileData = {
                    real_name: document.getElementById('profileRealName').value,
                    email: document.getElementById('profileEmail').value || null,
                    phone: document.getElementById('profilePhone').value || null,
                    department: document.getElementById('profileDepartment').value || null
                };
                
                const response = await fetch(`/api/admin/users/${adminUser.id}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(profileData)
                });
                
                if (response.ok) {
                    // 更新本地存储
                    const updatedUser = { ...adminUser, ...profileData };
                    localStorage.setItem('adminUser', JSON.stringify(updatedUser));
                    document.getElementById('adminName').textContent = updatedUser.real_name || '管理员';
                    
                    alert('个人资料更新成功');
                } else {
                    const result = await response.json();
                    alert(result.message || '更新失败');
                }
            } catch (error) {
                console.error('更新个人资料失败:', error);
                alert('更新失败');
            }
        }

        // 显示修改密码模态框
        function showChangePasswordModal() {
            document.getElementById('changePasswordForm').reset();
            new bootstrap.Modal(document.getElementById('changePasswordModal')).show();
        }

        // 提交修改密码
        async function submitChangePassword() {
            try {
                const currentPassword = document.getElementById('currentPassword').value;
                const newPassword = document.getElementById('newPassword').value;
                const confirmNewPassword = document.getElementById('confirmNewPassword').value;
                
                if (newPassword.length < 6) {
                    alert('新密码长度至少6个字符');
                    return;
                }
                
                if (newPassword !== confirmNewPassword) {
                    alert('两次输入的新密码不一致');
                    return;
                }
                
                const token = localStorage.getItem('adminToken');
                const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
                
                const response = await fetch(`/api/admin/users/${adminUser.id}/change-password`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        current_password: currentPassword,
                        new_password: newPassword
                    })
                });
                
                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('changePasswordModal')).hide();
                    alert('密码修改成功，请重新登录');
                    logout();
                } else {
                    const result = await response.json();
                    alert(result.message || '密码修改失败');
                }
            } catch (error) {
                console.error('修改密码失败:', error);
                alert('密码修改失败');
            }
        }

        // 管理线索分类
        function manageClueCategoriesModal() {
            alert('线索分类管理功能开发中...');
        }

        // 备份数据
        function backupData() {
            if (confirm('确定要备份系统数据吗？这可能需要一些时间。')) {
                alert('数据备份功能开发中...');
            }
        }

        // 查看系统日志
        function viewSystemLogs() {
            alert('系统日志查看功能开发中...');
        }

        // 清理缓存
        function clearCache() {
            if (confirm('确定要清理系统缓存吗？')) {
                alert('缓存清理功能开发中...');
            }
        }

        // 工具函数
        function getRoleText(role) {
            const roleMap = {
                'super_admin': '超级管理员',
                'admin': '管理员',
                'operator': '操作员',
                'viewer': '查看者'
            };
            return roleMap[role] || role;
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            window.location.href = '/admin/login.html';
        }
    </script>
</body>
</html> 